﻿using System.ComponentModel.Composition;
using Cubicle.Core.Interfaces;

namespace Cubicle.Core.Processors.Construct
{
    [Export("Cubicle.Processors.Construct.ConstructProcessor", typeof(IProcessor<InstructionRequest>))]
    [ExportMetadata("Name", "ConstructProcessor")]
    [ExportMetadata("Description", "A constructor invoker.")]
    public class ConstructProcessor : InstructionRequestProcessor
    {
        #region Overrides of Processor<ConstructionRequest>

        public ConstructProcessor() : base(RequestType.Construct) { }

        public override InstructionRequest ConditionalProcess(InstructionRequest request)
        {
            if (request.TargetConstructor == null)
            {
                request.Fail("No constructor to invoke.");
                return request;
            }

            // Before create event
            var args = new InstructionEventArgs(InstructionEventType.BeforeCreate, request);
            RaiseProcessorEvent(this, args);

            var result = request.TargetConstructor.Invoke(request.Parameters);

            // After create event
            args = new InstructionEventArgs(InstructionEventType.AfterCreate, request);
            RaiseProcessorEvent(this, args);

            request.Complete(result);
            return request;
        }

        #endregion
    }
}   